package cn.edu.java.serializable;


import lombok.AllArgsConstructor;
import lombok.ToString;

import java.io.*;

@AllArgsConstructor
@ToString
public class Employee implements java.io.Serializable {
    private static final long serialVersionUID = 6529685098267757690L;

    public String name;
    public String address;
    // 一旦变量被transient修饰，变量将不再是对象持久化的一部分，该变量内容在序列化后无法获得访问。
    // transient关键字只能修饰变量，而不能修饰方法和类。
    public transient int SSN;
    // 被transient关键字修饰的变量不再能被序列化，一个静态变量不管是否被transient修饰，均不能被序列化。
    public static int number;
    public void mailCheck()
    {
        System.out.println("Mailing a check to " + name
                + " " + address);
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
//        Employee.serialize();
        Employee.deserialize();
    }

    public static void serialize() throws IOException {
        Employee employee = new Employee("join", "group", 123456);
        employee.number = 20;

        FileOutputStream outputStream = new FileOutputStream("src/main/java/cn/edu/java/serializable/employee.ser");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(employee);
        objectOutputStream.close();
        outputStream.close();
        System.out.println("Serialized data is saved");
    }

    public static void deserialize() throws IOException, ClassNotFoundException {
        FileInputStream fileIn = new FileInputStream("src/main/java/cn/edu/java/serializable/employee.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);
        Employee employee = (Employee) in.readObject();
        in.close();
        fileIn.close();

        System.out.println("Deserialized Employee...");
        System.out.println(employee);
        System.out.println(employee.number);
    }
}
